import logging
import random
import re

from flask import abort
from flask import current_app, jsonify
from flask import g
from flask import make_response
from flask import redirect
from flask import render_template
from flask import request
from flask import session

from info import constants, db
from info import redis_store
from info.libs.yuntongxun.sms import CCP
from info.models import User, Category, News
from info.utils.captcha.captcha import captcha
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET
from . import user_blue

@user_blue.route('/other_news_list')
def other_news_list():
    """返回指定用户的发布的新闻"""

    # 1. 取参数
    other_id = request.args.get("user_id")
    page = request.args.get("p", 1)

    # 2. 判断参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")

    if not other:
        return jsonify(errno=RET.NODATA, errmsg="当前用户不存在")

    try:
        paginate = other.news_list.paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        # 获取当前页数据
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")

    news_dict_li = []
    for news_item in news_li:
        news_dict_li.append(news_item.to_basic_dict())

    data = {
        "news_list": news_dict_li,
        "total_page": total_page,
        "current_page": current_page
    }
    return jsonify(errno=RET.OK, errmsg="OK", data=data)

@user_blue.route('/other_info')
@user_login_data
def other_info():

    user = g.user

    # 去查询其他人的用户信息
    other_id = request.args.get("user_id")

    if not other_id:
        abort(404)

    # 查询指定id的用户信息
    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)

    if not other:
        abort(404)

    is_followed = False
    # if 当前新闻有作者，并且 当前登录用户已关注过这个用户
    if other and user:
        # if user 是否关注过 news.user
        if other in user.followed:
            is_followed = True

    data = {
        "is_followed": is_followed,
        "user": g.user.to_dict() if g.user else None,
        "other_info": other.to_dict()
    }
    return render_template('news/other.html', data=data)


@user_blue.route('/user_follow')
@user_login_data
def user_follow():
    # 获取页数
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    user = g.user

    follows = []
    current_page = 1
    total_page = 1
    try:
        paginate = user.followed.paginate(p, constants.USER_FOLLOWED_MAX_COUNT, False)
        # 获取当前页数据
        follows = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    user_dict_li = []

    for follow_user in follows:
        user_dict_li.append(follow_user.to_dict())
    data = {"users": user_dict_li, "total_page": total_page, "current_page": current_page}
    return render_template('news/user_follow.html', data=data)


@user_blue.route('/news_list')
@user_login_data
def news_list():
    # 获取页数
    page = request.args.get("page", 1)

    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    user = g.user
    news_models = []
    current_page = 1
    total_page = 1
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        # 获取当前页数据
        news_models = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []
    for news_item in news_models:
        news_dict_li.append(news_item.to_review_dict())

    data = {
        "news_list": news_dict_li,
        "total_page": total_page,
        "current_page": current_page
    }
    return render_template('news/user_news_list.html', data=data)


@user_blue.route('/news_release',methods =["POST",'GET'])
@user_login_data
def news_release():
    # GET 请求，需要返回分类数据
    if request.method=='GET':
        category_models = []
        try:
            category_models = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
        # 模型转列表
        category_list = []
        for category in category_models:
            category_list.append(category.to_dict())

        # 删除最新的分类
        category_list.pop(0)
        data = {
            'category':category_list
        }
        return render_template('news/user_news_release.html',data=data)

    # POST 请求--->获取数据-->上传头像--->添加数据
    # 一.获取要提交的数据
    title = request.form.get('title')
    # 新闻来源
    source = '个人发布'
    # 新闻摘要
    digest = request.form.get('digest')
    # 新闻内容
    content = request.form.get('content')
    # 首页图像，
    index_image = request.files.get('index_image')
    # 分类ID
    category_id = request.form.get('category_id')

    # 二.参数校验
    # 2.1 完整性
    if not all([title,source,digest,content,index_image,category_id]):
        return jsonify(errno = RET.PARAMERR,errmsg = '参数有误')
    # 2.2 获取图像
    try:
        image_data = index_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.PARAMERR,errmsg = '参数有误')

    # 2.3 分类ID(类型，是否有值)
    try:
        category_id = int(category_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.PARAMERR,errmsg = "参数错误")

    try:
        category_models = Category.query.get(category_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = "数据库错误")

    if not category_models:
        return jsonify(errno = RET.NODATA,errmsg='无分类数据')

    # 三.逻辑处理
    # 3.1 上传图像
    try:
        image_name = storage(image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.THIRDERR,errmsg = "七牛云上传图像错误")

    # 3.2 创建新闻模型
    news = News()
    news.title = title
    news.digest = digest
    news.source = source
    news.content = content
    news.category_id = category_id
    news.user_id = g.user.id # 新闻发布人
    # 1代表待审核状态
    news.status = 1 # 默认是待审核状态
    # 这里需要加上前缀来保存(抓取其他的网站的图片都是有前缀的，我们需要保持统一)
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + image_name

    # 3.保存到数据库
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno = RET.DBERR,errmsg = "保存数据库错误")
    # 四.返回数据
    return jsonify(errno = RET.OK,errmsg='发布成功，等待审核')


@user_blue.route('/pic_info', methods=["GET", "POST"])
@user_login_data
def pic_info():
    user = g.user

    # GET请求，渲染模板
    if request.method=='GET':
        return render_template('news/user_pic_info.html', data={"user": user.to_dict()})

    # POST请求
    # 一.获取参数&校验参数
    try:
        avatar_data = request.files.get('avatar').read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno =RET.PARAMERR,errmsg = '参数错误')

    # 二.逻辑处理
    # 2.1 上传七牛云
    try:
        avatar_name = storage(avatar_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno =RET.THIRDERR,errmsg = '七牛云上传失败')

    #2.2 添加数据库
    user.avatar_url = avatar_name

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollbakc()
        current_app.logger.error(e)
        return jsonify(errno =RET.DBERR,errmsg = '数据库错误')

    # 三.返回数据---->拼接前缀
    return jsonify(errno=RET.OK, errmsg="OK", data={"avatar_url": constants.QINIU_DOMIN_PREFIX + avatar_name})




@user_blue.route('/collection')
@user_login_data
def collection():
    # 获取页码
    page = request.args.get('page',1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        # 如果页码不是int类型的数据，肯能在查询数据库时有问题
        page = 1

    # 查询数据库
    user = g.user
    collection_models = None
    current_page = 1
    total_page = 1
    try:
        # 进行分页数据查询
        paginate = user.collection_news.paginate(page,2,False)
        # 获取分页数据
        collection_models = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    # 模型转字典
    collection_list = []
    for collection in collection_models:
        collection_list.append(collection.to_dict())

    # 返回数据
    data = {
        'collection_list':collection_list,
        'current_page':current_page,
        'total_page':total_page
    }

    return render_template('news/user_collection.html',data = data)


@user_blue.route('/pass_info', methods=['GET', 'POST'])
@user_login_data
def pass_info():
    if request.method == "GET":
        return render_template('news/user_pass_info.html')

    # 1. 获取到传入参数
    old_password = request.json.get("old_password")
    new_password = request.json.get("new_password")

    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 2. 获取当前登录用户的信息
    user = g.user

    if not user.check_password(old_password):
        return jsonify(errno=RET.PWDERR, errmsg="原密码错误")

    # 更新数据
    user.password = new_password

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

    return jsonify(errno=RET.OK, errmsg="保存成功")

# 每一个标签页，都需要一个路由匹配，因为我们需要传入数据渲染的
@user_blue.route('/base_info',methods=['GET','POST'])
@user_login_data
def base_info():
    """
        用户基本信息
        1. 获取用户登录信息
        2. 获取到传入参数
        3. 更新并保存数据
        4. 返回结果
        """

    # 1. 获取当前登录用户的信息
    user = g.user
    if request.method == "GET":
        return render_template('news/user_base_info.html', data={"user": user.to_dict()})

    # 2. 获取到传入参数
    nick_name = request.json.get("nick_name")
    gender = request.json.get("gender")
    signature = request.json.get("signature")

    if not all([nick_name, gender, signature]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    if gender not in ['MAN', 'WOMAN']:
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 3. 更新并保存数据
    user.nick_name = nick_name
    user.gender = gender
    user.signature = signature
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

    # 将 session 中保存的数据进行实时更新
    session["nick_name"] = nick_name

    # 4. 返回响应
    return jsonify(errno=RET.OK, errmsg="更新成功")

@user_blue.route('/info')
@user_login_data
def user_info():

    user = g.user
    # 个人中心界面，需要在这里判断一次用户为空的情况就可以了
    # 因为此时，父模板都无法加载，会直接返回首页，不会加载子模板
    if not user:
        return redirect('/')

    data = {
        'user': user.to_dict() if user else None
    }
    return render_template('news/user.html',data=data)